package cn.bluedot.tea.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class BeanUtil {
	
	public static <T, R> R convertBean(T source, Class<R> targetClazz)
            throws IllegalArgumentException, IllegalAccessException {
        R result = null;
        try {
            result = targetClazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            System.out.println("constructing the result is failed ");
            e.printStackTrace();
        }
        // get the source class
        Class<? extends Object> sourceClazz = source.getClass();
        // 获取所有的属性
        Field[] sourceFields = sourceClazz.getDeclaredFields();
        Field[] targetFields = targetClazz.getDeclaredFields();

        // 使用foreach进行遍历
        for (Field sourceField : sourceFields) {
            // 开放权限
            sourceField.setAccessible(true);
            for (Field targetField : targetFields) {
                if (targetField.getName().equals(sourceField.getName())
                        && targetField.getType().equals(sourceField.getType())) {
                    int mod = targetField.getModifiers();
                    if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                        continue;
                    }
                    targetField.setAccessible(true);
                    targetField.set(result, sourceField.get(source));
                    break;
                }
            }
        }
        return result;
    }

}
